import os
import random
import string
from PIL import Image, ImageFont, ImageDraw,ImageFilter


class ImageVerify:
    def __init__(self,width=140,height=40, length=4, size=28):
        self.width = width
        self.height = height
        self.length = length
        self.size = size


    def random_str(self):
        source = string.ascii_letters + string.digits

        return ''.join(random.sample(source,self.length))

    # 颜色干扰
    def random_color(self,start=0, end=255):
        res = (random.randint(0,255) for i in range (3))
        return tuple(res)

    # 线条干扰
    def random_lines(self,draw):
        for i in range(self.length):
            lines = [(random.randint(0,self.width),random.randint(0,self.height)) for i in range(2)]
            draw.line(list(lines), fill=self.random_color(start=100), width= 2 )
    # 干扰点
    def random_points(self,draw,rate):
        for x in range(self.width):
            for y in range(self.height):
                if random.randint(1, 100)<= rate:
                    draw.point((x,y), fill=self.random_color(start=150))


    def image_code(self):
        image = Image.new('RGB',(self.width, self.height),(255,255,255))
        file = os.path.dirname(os.path.abspath(__file__))
        font = ImageFont.truetype(f'{file}/HYYakuHei-85W.ttf',self.size)
        draw = ImageDraw.Draw(image)
        code = self.random_str()

        for t in range(self.length):
            draw.text((30*t+15,3),code[t], font=font,fill= self.random_color(end=60)),
        self.random_lines(draw)
        self.random_points(draw,10)
        image = image.filter(ImageFilter.BLUR)
        print(code)

        return image,code

# if __name__ =='__main__':
#     imgVerify= ImageVerify()
#     img = imgVerify.image_code()
#     with open('test.png','wb') as f:
#         img.save(f)
